//
//  UIColor.swift
//  vgbox
//
//  Created by 宋海胜 on 2019/6/26.
//  Copyright © 2019 Swift Xcode. All rights reserved.
//

import UIKit

extension UIColor {
    
    /// RGB
    convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1.0) {
        self.init(
            red:r,
            green:g,
            blue:b,
            alpha:a
        )
    }
    
    /// 传入16进制
    convenience init(hex: Int, alpha: CGFloat = 1.0) {
        self.init(red: ((CGFloat)((hex & 0xFF0000) >> 16)) / 255.0,
        green: ((CGFloat)((hex & 0xFF00) >> 8)) / 255.0,
        blue: ((CGFloat)(hex & 0xFF)) / 255.0,
        alpha: alpha)
    }
    
    /**
         Make color with hex string
         - parameter hex: 16进制字符串(eg. #0x00eeee or #0X00eeee or 0x00eeee or 0X00eeee or 00eeee)
         - returns: RGB
         */
        static func hexString(hex: String, alpha: CGFloat = 1.0) -> UIColor {
            
            var cString: NSString = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased() as NSString
            
            if (cString.hasPrefix("#")) {
                cString = cString.substring(from: 1) as NSString
            }
            if (cString.hasPrefix("0X") || cString.hasPrefix("0x")) {
                cString = cString.substring(from: 2) as NSString
            }
            
            if (cString.length != 6) {
                return UIColor.gray
            }
            
            let rString = cString.substring(with: NSMakeRange(0, 2))
            let gString = cString.substring(with: NSMakeRange(2, 2))
            let bString = cString.substring(with: NSMakeRange(4, 2))
            
            var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0
            
            Scanner(string: rString).scanHexInt32(&r)
            Scanner(string: gString).scanHexInt32(&g)
            Scanner(string: bString).scanHexInt32(&b)
            
            return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha)
        }
}


